﻿package ru.volgogradetzzz.utils
{
	import flash.events.TimerEvent;	
	import flash.utils.getTimer;
	import flash.utils.Timer;

	public class PausableTimer extends Timer 
	{
		private var _startTime:Number;
		private var _initialDelay:Number;
		private var _repeatCount:int;
		private var _paused:Boolean = false;
		private var d:Number;
		
		public function PausableTimer(delay:Number, repeatCount:int = 0)
		{
			super(delay, repeatCount);
			_initialDelay = delay;
			_repeatCount = repeatCount;
			
			addEventListener(TimerEvent.TIMER, onTimer, false, 0, true);
		}
		
		private function onTimer(event:TimerEvent):void
		{
			_startTime = getTimer();
			delay = _initialDelay;
		}
		
		override public function start():void
		{
			_paused = false;
			_startTime = getTimer();
			super.start();
		}
		
		public function pause():void
		{
			if(running)
			{
				_paused = true;
				stop();
				
				d = delay - (getTimer() - _startTime);
				if (d < 1) d = 1;
				delay = d;
			}
		}
		
		public function get paused():Boolean
		{
			return _paused;
		}
	}
}